﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Globalization;
using System.Text;

namespace VSM.Parts
{
    public partial class Deposit : System.Web.UI.Page
    {
        #region Fields

        private string TblHeaderName = "U_Deposit_Header";
        private string TblLineName = "U_Deposit_Detail";
        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Cache.SetCacheability(HttpCacheability.Private);

            if (Session[Utils.AppConstants.ID_User] == null
                || Session[Utils.AppConstants.Password] == null
                || Session[Utils.AppConstants.ID_Dealer] == null)
            {
                Response.Redirect("../../../Login.aspx");
            }
            if (!IsPostBack)
            {
                this.grvWTQ1.DataSource = null;
                this.grvWTQ1.DataBind();
            }


        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvWTQ1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.grvWTQ1.PageIndex = e.NewPageIndex;
            DataTable tblWTQ1 = (DataTable)Session["Deposit"];
            BindData(tblWTQ1);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lnkDelete_Click(object sender, EventArgs e)
        {
            try
            {
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((LinkButton)sender).Parent).Parent;
                Label lblItemCode = (Label)row.FindControl("lblNo");
                DataTable tblITransRqst = (DataTable)Session["Deposit"];
                if (tblITransRqst != null)
                {
                    DataRow[] rupdate = tblITransRqst.Select("No='" + lblItemCode.Text + "'");
                    tblITransRqst.Rows.Remove(rupdate[0]);
                    this.grvWTQ1.EditIndex = -1;
                    BindData((DataTable)Session["Deposit"]);
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvWTQ1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");
                e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");
                e.Row.Attributes["style"] = "cursor:pointer";

                LinkButton lnkDelete = (LinkButton)e.Row.FindControl("lnkDelete");
                HiddenField hdnDetailID = (HiddenField)e.Row.FindControl("hdnDetailID");
                RadioButton chkActive = (RadioButton)e.Row.FindControl("chkActive");
                TextBox txtDepositDate = (TextBox)e.Row.FindControl("txtDepositDate");
                TextBox txtDepositAmt = (TextBox)e.Row.FindControl("txtDepositAmt");
                ImageButton imgDeldate = (ImageButton)e.Row.FindControl("imgDeldate");
                if (chkActive.Checked)
                {
                    txtDepositAmt.Enabled = true;
                    txtDepositDate.Enabled = true;
                    imgDeldate.Enabled = true;
                }
                if (hdnDetailID.Value.Length > 0)
                {
                    lnkDelete.Enabled = false;
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtOrderQuantity_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtQuantity = (TextBox)row.FindControl("txtQuantity");
                if (txtQuantity.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input quantity');", true);
                    txtQuantity.Focus();
                    return;
                }
                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tblITransRqst = (DataTable)Session["WTQ1RqstTable"];
                if (tblITransRqst != null)
                {
                    DataRow[] rupdate = tblITransRqst.Select("No=" + lblNo.Text);
                    if (rupdate.Length > 0)
                    {
                        GeneralFunctions GF = new GeneralFunctions();
                        rupdate[0]["Quantity"] = GF.FormatNumeric(GF.ResetFormatNumeric(txtQuantity.Text), "QtyDec");
                    }
                }

                this.grvWTQ1.EditIndex = -1;

                BindData(tblITransRqst);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void EditItem(object sender, GridViewEditEventArgs e)
        {
            this.grvWTQ1.EditIndex = e.NewEditIndex;
            BindData((DataTable)Session["WTQ1RqstTable"]);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
        {
            e.Cancel = true;
            this.grvWTQ1.EditIndex = -1;
            BindData((DataTable)Session["WTQ1RqstTable"]);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void DeleteItem(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                e.Cancel = true;
                GridViewRow row = (GridViewRow)this.grvWTQ1.Rows[e.RowIndex];
                Label lblItemCode = (Label)row.FindControl("lblItemCode");
                DataTable tblITransRqst = (DataTable)Session["WTQ1RqstTable"];
                if (tblITransRqst != null)
                {
                    DataRow[] rupdate = tblITransRqst.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        Dictionary<string, string> dicItem = (Dictionary<string, string>)Session["ChosenItem"];
                        if (dicItem != null)
                        {
                            if (dicItem.ContainsKey(rupdate[0]["ItemCode"].ToString()))
                            {
                                dicItem.Remove(rupdate[0]["ItemCode"].ToString());
                            }
                        }
                        tblITransRqst.Rows.Remove(rupdate[0]);
                    }
                    this.grvWTQ1.EditIndex = -1;
                    BindData((DataTable)Session["WTQ1RqstTable"]);

                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void UpdateItem(object sender, GridViewUpdateEventArgs e)
        {
            try
            {
                ViewState["rowindex"] = e.RowIndex;
                GridViewRow row = (GridViewRow)this.grvWTQ1.Rows[e.RowIndex];
                TextBox txtQuantity = (TextBox)row.FindControl("txtOrderQuantity");
                if (txtQuantity.Text.Trim().Length == 0 || int.Parse(txtQuantity.Text.Trim()) == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('In Quantity column, enter whole number greater than 0');", true);
                    txtQuantity.Focus();
                    return;
                }
                Label lblItemCode = (Label)row.FindControl("lblItemCode");

                DataTable tblItransRqst = (DataTable)Session["WTQ1RqstTable"];
                if (tblItransRqst != null)
                {
                    DataRow[] rupdate = tblItransRqst.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["Quantity"] = txtQuantity.Text;

                    }

                    this.grvWTQ1.EditIndex = -1;

                    BindData(tblItransRqst);

                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="tblData"></param>
        private void BindData(DataTable tblData)
        {
            Session["Deposit"] = tblData;
            this.grvWTQ1.DataSource = tblData;
            this.grvWTQ1.DataBind();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoadComplete(EventArgs e)
        {
            try
            {
                base.OnLoadComplete(e);
                if (this.Request["__EVENTARGUMENT"] != null && this.Request["__EVENTARGUMENT"].ToString() != "")
                {
                    string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                    GridViewRow grdvRow = null;
                    MasterData obj = new MasterData();
                    switch (this.Request["__EVENTARGUMENT"].ToString())
                    {
                        case "SelectBP":
                            ViewState["rowindex"] = -1;
                            this.hdnMasterID.Value = string.Empty;
                            this.lblError.Visible = false;
                            Session["Deposit"] = null;
                            grdvRow = Session["ChosenBP"] != null ? (GridViewRow)Session["ChosenBP"] : null;
                            this.txtCustomerCode.Text = ((Label)grdvRow.FindControl("lblCardCode")).Text;
                            this.txtCustomerName.Text = ((Label)grdvRow.FindControl("lblCardName")).Text;
                            LoadData(dbType, obj);
                            Session["ChosenBP"] = null;
                            break;

                        default:
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        private void LoadData(string dbType, MasterData obj)
        {
            DataSet ds = obj.GetDeposit(this.txtCustomerCode.Text.Trim(), dbType, Session[Utils.AppConstants.U_Department].ToString());
            if (ds != null && ds.Tables.Count > 0)
            {
                DataTable tbContent = BuildContents(ds.Tables[0]);
                BindData(tbContent);
            }
        }
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvWTQ1_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                GridViewRow myRow = e.Row;
                Label lblNo = myRow.FindControl("lblNo") as Label;
                lblNo.Text = (myRow.RowIndex + 1).ToString();
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtPODate_TextChanged(object sender, EventArgs e)
        {
            try
            {
                //Check Valid Date
                this.btnAddItems.Enabled = true;
            }
            catch
            {
                this.btnAddItems.Enabled = false;
            }
        }
        /// <summary>
        /// 
        /// </summary>

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;

                MasterData obj = new MasterData();
                string errMessage = obj.UpdateDeposit(_collectData(), dbType);

                if (errMessage.Length > 0)
                {
                    Session["errorMessage"] = errMessage;
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + errMessage + "','');", true);
                }
                else
                {
                    Session["successMessage"] = "Operation complete sucessful!";
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);
                    LoadData(dbType, obj);
                }
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + ex.ToString() + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            CloseCancel(true);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnClose_Click(object sender, EventArgs e)
        {
            CloseCancel(false);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="isClose"></param>
        private void CloseCancel(bool isClose)
        {
            try
            {

            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
            }
            this.lblError.Visible = true;
        }

        public DataSet _collectData()
        {
            try
            {
                string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
                //Update table header
                DataTable dtHeader = new DataTable("U_Deposit_Header");
                dtHeader.Columns.Add("ID");
                dtHeader.Columns.Add("CardCode");
                dtHeader.Columns.Add("Remarks");
                dtHeader.Columns.Add("Dealer_ID");
                dtHeader.Columns.Add("U_Department");

                DataRow drHeader = dtHeader.NewRow();
                drHeader["ID"] = this.hdnMasterID.Value;
                drHeader["CardCode"] = this.txtCustomerCode.Text;
                drHeader["Remarks"] = this.txtRemarks.Text;
                drHeader["Dealer_ID"] = Session[Utils.AppConstants.ID_Dealer].ToString();
                drHeader["U_Department"] = Utils.AppConstants.PARTS;

                dtHeader.Rows.Add(drHeader);

                DataSet ds = new DataSet("DS");
                dtHeader.TableName = TblHeaderName;

                ds.Tables.Add(dtHeader.Copy());

                DataTable dt = new DataTable("U_Deposit_Detail");
                dt.Columns.Add("ID");
                dt.Columns.Add("HeaderID");
                dt.Columns.Add("DepositAmt");
                dt.Columns.Add("DepositLimit");
                dt.Columns.Add("DepositDate");
                dt.Columns.Add("IsActive");
                dt.TableName = TblLineName;

                DataTable tbData = (DataTable)Session["Deposit"];
                foreach (DataRow dr in tbData.Rows)
                {
                    DataRow rowNew = dt.NewRow();
                    rowNew["ID"] = dr["ID"].ToString();
                    rowNew["HeaderID"] = dr["HeaderID"];
                    rowNew["DepositAmt"] = GF.Object2Double((object)GF.ResetFormatNumeric(dr["DepositAmt"].ToString()), "SumDec");
                    rowNew["DepositLimit"] = GF.Object2Double((object)GF.ResetFormatNumeric(dr["DepositLimit"].ToString()), "SumDec");
                    rowNew["DepositDate"] = Utils.AppConstants.ConvertToDate(dr["DepositDate"].ToString());
                    rowNew["IsActive"] = dr["IsActive"];

                    dt.Rows.Add(rowNew);
                }
                ds.Tables.Add(dt.Copy());
                return ds;
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + ex.ToString() + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
            return null;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtDepositAmt_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtQuantity = (TextBox)row.FindControl("txtDepositAmt");
                if (txtQuantity.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input amount');", true);
                    txtQuantity.Focus();
                    return;
                }
                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tb = (DataTable)Session["Deposit"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("No='" + lblNo.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["DepositAmt"] = GF.FormatNumeric(txtQuantity.Text, "SumDec");
                        double limit = (double.Parse(txtQuantity.Text) * 120) / 100;
                        rupdate[0]["DepositLimit"] = GF.FormatNumeric(limit.ToString(), "SumDec");
                    }
                }

                this.grvWTQ1.EditIndex = -1;

                BindData(tb);
                //Session["Deposit"] = tb;
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtDepositDate_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtQuantity = (TextBox)row.FindControl("txtDepositDate");
                if (txtQuantity.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input date');", true);
                    txtQuantity.Focus();
                    return;
                }
                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tb = (DataTable)Session["Deposit"];
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("No='" + lblNo.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["DepositDate"] = txtQuantity.Text;
                    }
                }

                this.grvWTQ1.EditIndex = -1;

                Session["Deposit"] = tb;
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        private DataTable BuildContents(DataTable dtContent)
        {
            DataTable dt = new DataTable("Deposit");
            dt.Columns.Add("No");
            dt.Columns.Add("HeaderID");
            dt.Columns.Add("DepositAmt");
            dt.Columns.Add("DepositLimit");
            dt.Columns.Add("DepositDate");
            dt.Columns.Add("IsActive");
            dt.Columns.Add("ID");
            if (dtContent != null)
            {
                string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
                int i = 1;
                foreach (DataRow dr in dtContent.Rows)
                {
                    this.txtRemarks.Text = dr["Remarks"].ToString();
                    this.hdnMasterID.Value = dr["ID"].ToString();
                    DataRow row = dt.NewRow();
                    row["No"] = i;
                    row["HeaderID"] = dr["HeaderID"];
                    row["DepositAmt"] = GF.FormatNumeric(dr["DepositAmt"].ToString(), "SumDec");
                    row["DepositLimit"] = GF.FormatNumeric(dr["DepositLimit"].ToString(), "SumDec");
                    row["DepositDate"] = Convert.ToDateTime(dr["DepositDate"].ToString()).ToString(Utils.AppConstants.DATE);
                    row["IsActive"] =  dr["IsActive"];
                    row["ID"] = dr["DetailID"];
                    dt.Rows.Add(row);
                    i++;
                }
            }
            return dt;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnAddItems_Click(object sender, EventArgs e)
        {
            DataTable tb = (DataTable)Session["Deposit"];
            if (tb != null)
            {
                DataRow rowNew = tb.NewRow();
                rowNew["No"] = (tb.Rows.Count + 1).ToString();
                rowNew["DepositAmt"] = "0.00";
                rowNew["DepositDate"] = DateTime.Now.ToString(Utils.AppConstants.DATE);
                rowNew["IsActive"] = "False";
                tb.Rows.Add(rowNew);
                BindData(tb);
            }
        }
        protected void chkActive_OnCheckedChanged(object sender, EventArgs e)
        {
            try
            {
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((RadioButton)sender).Parent).Parent;
                RadioButton chkActive = (RadioButton)row.FindControl("chkActive");
                TextBox txtDepositDate = (TextBox)row.FindControl("txtDepositDate");
                TextBox txtDepositAmt = (TextBox)row.FindControl("txtDepositAmt");
                ImageButton imgDeldate = (ImageButton)row.FindControl("imgDeldate");
                
                DataTable tb = (DataTable)Session["Deposit"];
                foreach (GridViewRow rowView in this.grvWTQ1.Rows)
                {
                    RadioButton chkActiverowView = (RadioButton)rowView.FindControl("chkActive");
                    chkActiverowView.Checked = false;
                    TextBox txtDepositDaterowView = (TextBox)rowView.FindControl("txtDepositDate");
                    txtDepositDaterowView.Enabled = false;
                    TextBox txtDepositAmtrowView = (TextBox)rowView.FindControl("txtDepositAmt");
                    txtDepositAmtrowView.Enabled = false;
                    ImageButton imgDeldaterowView = (ImageButton)rowView.FindControl("imgDeldate");
                    imgDeldaterowView.Enabled = false;

                    Label lblNo = (Label)rowView.FindControl("lblNo");
                    if (tb != null)
                    {
                        DataRow[] rupdate = tb.Select("No='" + lblNo.Text + "'");
                        if (rupdate.Length > 0)
                        {
                            rupdate[0]["IsActive"] = false;
                        }
                    }
                }
                Label lblNoCheck = (Label)row.FindControl("lblNo");
                if (tb != null)
                {
                    DataRow[] rupdate = tb.Select("No='" + lblNoCheck.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["IsActive"] = true;
                    }
                }
                //BindData(tb);
                Session["Deposit"] = tb;
                chkActive = (RadioButton)row.FindControl("chkActive");
                txtDepositDate = (TextBox)row.FindControl("txtDepositDate");
                txtDepositAmt = (TextBox)row.FindControl("txtDepositAmt");
                imgDeldate = (ImageButton)row.FindControl("imgDeldate");
                chkActive.Checked = true;
                txtDepositDate.Enabled = true;
                txtDepositAmt.Enabled = true;
                imgDeldate.Enabled = true;
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
    }
}